import {
  DetailResult,
  EcgData,
  QRSAnaResponse,
  RawEcgParam,
  Study,
  type EcgXWave,
  type VerticalLine,
} from '@/pages/types/type';
import { postRequestInit, urlPrefix } from '@/utils/http';
import {
  Button,
  Checkbox,
  Picker,
  Popup,
  Radio,
  Space,
  Tag,
  Toast,
} from 'antd-mobile';
import { ToastHandler } from 'antd-mobile/es/components/toast';
import React, {
  Dispatch,
  SetStateAction,
  useEffect,
  useRef,
  useState,
} from 'react';
import styles from './AnalysisOverlay.less';

interface AnalysisOverlayProps {
  wave: EcgXWave;
  ecgData: EcgData;
  study: Study;
  visible: boolean;
  onSave: (e: string) => void;
  onClose: () => void;
  ecgParams: RawEcgParam[];
  verticalLines: VerticalLine[];
  setEcgParams: Dispatch<SetStateAction<RawEcgParam[]>>;
  setVerticalLines: Dispatch<SetStateAction<VerticalLine[]>>;
  autoAnalysisResult: string;
  setAutoAnalysisResult: Dispatch<SetStateAction<string>>;
}

type LeaderColor = {
  name: string;
  color: string;
};

const leaderColors: LeaderColor[] = [
  { name: 'I', color: '#808069' },
  { name: 'II', color: '#0000FF' },
  { name: 'III', color: '#00FF00' },
  { name: 'AVR', color: '#228B22' },
  { name: 'AVL', color: '#9C661F' },
  { name: 'AVF', color: '#8B864E' },
  { name: 'V1', color: '#D2B48C' },
  { name: 'V2', color: '#FF0000' },
  { name: 'V3', color: '#E3170D' },
  { name: 'V4', color: '#FF8000' },
  { name: 'V5', color: '#ED9121' },
  { name: 'V6', color: '#082E54' },
];

type VLine = {
  text: string;

  /** 当前坐标 */
  iPos: number;

  /**
   * 是否被选中
   */
  selected: boolean;

  /**
   * 下方文本，一般是中文
   */
  bText: string;

  /**
   * 是否为峰值类型
   */
  isPeak: boolean;

  /**
   * 用于跟后端枚举值对应
   */
  type: string;
};

// type HMoveState = {
//   index: number;
//   moving: boolean;
//   distance: number;
// };

const AnalysisOverlay: React.FC<AnalysisOverlayProps> = ({
  visible,
  onClose,
  wave,
  ecgData,
  study,
  onSave,
  ecgParams,
  setEcgParams,
  setVerticalLines,
  verticalLines,
  autoAnalysisResult,
  setAutoAnalysisResult,
}) => {
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const [activeTab, setActiveTab] = useState(wave.avrWave[0].leadName);
  const [useLeadNames, setUseLeadNames] = useState<string[]>([
    wave.avrWave[0].leadName,
  ]);
  const [showPeak, setShowPeak] = useState<boolean>(false);
  const [showAllLeads, setShowAllLeads] = useState<boolean>(false);
  const [isMultiSelect, setIsMultiSelect] = useState<boolean>(false);
  // 导联选择模式：'single' | 'multi' | 'all'
  const [selectMode, setSelectMode] = useState<'single' | 'multi' | 'all'>(
    'single',
  );

  // 同步selectMode与原有状态
  useEffect(() => {
    if (showAllLeads) {
      setSelectMode('all');
    } else if (isMultiSelect) {
      setSelectMode('multi');
    } else {
      setSelectMode('single');
    }
  }, [showAllLeads, isMultiSelect]);
  // 导联选择弹窗状态
  const [leadSelectorVisible, setLeadSelectorVisible] =
    useState<boolean>(false);
  // 波型选择，是那个时间点上的波型，还是
  const [qrsIndex, setQrsIndex] = useState<string | number>('standard');

  // 当前选择的垂直线
  const [vLineName, setVLineName] = useState<string | undefined>();

  // 自动分析结果
  const [ingAutoAnalysisResult, setIngAutoAnalysisResult] =
    useState<string>(autoAnalysisResult);
  const [ingEcgParams, setIngEcgParams] = useState<RawEcgParam[]>(
    study.ecgParams,
  );

  // 拖拽状态
  const [dragState, setDragState] = useState<{
    isDragging: boolean;
    dragIndex: number;
    startX: number;
    isPeakMode: boolean;
  }>({ isDragging: false, dragIndex: -1, startX: 0, isPeakMode: false });

  // 初始加载状态，用于避免组件首次加载时触发分析
  const isInitialLoadRef = useRef<boolean>(true);

  // Tab切换状态，用于避免Tab切换时触发分析
  const isTabSwitchingRef = useRef<boolean>(false);

  // 悬浮状态
  const [hoverIndex, setHoverIndex] = useState<number>(-1);
  const [isHoveringPeak, setIsHoveringPeak] = useState<boolean>(false);

  // 添加窗口大小状态来触发重绘
  const [windowSize, setWindowSize] = useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });

  //const { verticalLines } = wave;
  const h400: number = 400;
  const getPosition = (typeName: string): number => {
    return (
      verticalLines.filter(({ type }) => type.value === typeName)[0]
        ?.position || h400
    );
  };

  // 用于分析时，进行提示
  const handler = useRef<ToastHandler>();

  const psRRMin: boolean = getPosition('PsRR') < 20;
  const PsRR = getPosition('PsRR');
  const [rr, setRR] = useState<number>(psRRMin ? h400 : PsRR);

  // 初始化垂直线，合并普通线和峰值线
  const [vLines, setVLines] = useState<VLine[]>([
    {
      text: 'PB',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsP1'),
      bText: 'P开始',
      isPeak: false,
      type: 'PsP1',
    },
    {
      text: 'PE',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsP2'),
      bText: 'P结束',
      isPeak: false,
      type: 'PsP2',
    },
    {
      text: 'Q',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsQQ'),
      bText: 'Q开始',
      isPeak: false,
      type: 'PsQQ',
    },
    {
      text: 'S',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsSS'),
      bText: 'S结束',
      isPeak: false,
      type: 'PsSS',
    },
    {
      text: 'TB',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsT1'),
      bText: 'T开始',
      isPeak: false,
      type: 'PsT1',
    },
    {
      text: 'TE',
      selected: false,
      iPos: psRRMin ? h400 : getPosition('PsT2'),
      bText: 'T结束',
      isPeak: false,
      type: 'PsT2',
    },
    {
      text: 'PP',
      selected: false,
      iPos: getPosition('PsPP'),
      bText: 'P波峰',
      isPeak: true,
      type: 'PsPP',
    },
    {
      text: 'RR',
      selected: false,
      iPos: getPosition('PsRR'),
      bText: 'R波峰',
      isPeak: true,
      type: 'PsRR',
    },
    {
      text: 'TT',
      selected: false,
      iPos: getPosition('PsTT'),
      bText: 'T波峰',
      isPeak: true,
      type: 'PsTT',
    },
  ]);

  useEffect(() => {
    console.log(vLines);
    // 如果是初始加载，跳过分析接口调用
    if (isInitialLoadRef.current) {
      isInitialLoadRef.current = false;
      return;
    }

    if (!dragState.isDragging && !isTabSwitchingRef.current) {
      handler.current = Toast.show({
        icon: 'loading',
        content: '正在分析...',
        maskClickable: false,
        duration: 0,
      });

      fetch(
        `${urlPrefix}/api/analysis/do-analyze`,
        postRequestInit({
          study: study.id,
          vLines: vLines.map(({ type, iPos: position }) => ({
            type,
            position,
          })),
        }),
      )
        .then(async (rsp: Response) => {
          if (rsp.ok) {
            await rsp
              .json()
              .then(
                async ({ data, code, msg }: DetailResult<QRSAnaResponse>) => {
                  if (code === 0) {
                    handler.current?.close();
                    const { autoAnalysisResult, AIPn, ecgParams } = data!;
                    setIngAutoAnalysisResult(autoAnalysisResult);
                    setIngEcgParams(ecgParams);
                  } else {
                    Toast.show({
                      icon: 'fail',
                      content: msg,
                      duration: 4000,
                    });
                  }
                },
              )
              .catch((reason) => {
                Toast.show({
                  icon: 'fail',
                  content: `执行失败：${reason}`,
                });
              });
          }
        })
        .catch((reason: any) => {
          Toast.show({
            icon: 'fail',
            content: `执行失败：${reason}`,
          });
        })
        .finally(() => {
          //handler.current?.close();
        });
    } // end 不是手动状态的改变才行

    // 重置Tab切换状态
    isTabSwitchingRef.current = false;
  }, [vLines]);

  // 独立的分析函数，用于拖拽结束后调用
  const callAnalysisAPI = () => {
    handler.current = Toast.show({
      icon: 'loading',
      content: '正在分析...',
      maskClickable: false,
      duration: 0,
    });

    fetch(
      `${urlPrefix}/api/analysis/do-analyze`,
      postRequestInit({
        study: study.id,
        vLines: vLines.map(({ type, iPos: position }) => ({ type, position })),
      }),
    )
      .then(async (rsp: Response) => {
        if (rsp.ok) {
          await rsp
            .json()
            .then(async ({ data, code, msg }: DetailResult<QRSAnaResponse>) => {
              if (code === 0) {
                handler.current?.close();
                const { autoAnalysisResult, ecgParams } = data!;
                setIngAutoAnalysisResult(autoAnalysisResult);
                setIngEcgParams(ecgParams);
              } else {
                Toast.show({
                  icon: 'fail',
                  content: msg,
                  duration: 4000,
                });
              }
            })
            .catch((reason) => {
              Toast.show({
                icon: 'fail',
                content: `执行失败：${reason}`,
              });
            });
        }
      })
      .catch((reason: any) => {
        Toast.show({
          icon: 'fail',
          content: `执行失败：${reason}`,
        });
      })
      .finally(() => {
        //handler.current?.close();
      });
  };

  // const getEventCoordinates = (
  //   e:
  //     | React.MouseEvent<HTMLCanvasElement>
  //     | React.TouchEvent<HTMLCanvasElement>,
  // ): XYTupple => {
  //   const canvas = canvasRef.current;
  //   if (!canvas) return { x: 0, y: 0 };

  //   const rect = canvas.getBoundingClientRect();

  //   // 判断是鼠标事件还是触摸事件
  //   if ('clientX' in e) {
  //     // 鼠标事件
  //     return {
  //       x: e.clientX - rect.left,
  //       y: e.clientY - rect.top,
  //     };
  //   } else {
  //     // 触摸事件
  //     const touch = e.touches[0];
  //     return {
  //       x: touch.clientX - rect.left,
  //       y: touch.clientY - rect.top,
  //     };
  //   }
  // };

  // 添加窗口大小改变监听器
  useEffect(() => {
    const handleResize = () => {
      setWindowSize({
        width: window.innerWidth,
        height: window.innerHeight,
      });
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');
    if (ctx && canvas) {
      const devicePixelRatio = window.devicePixelRatio || 1;
      const displayWidth = window.innerWidth - 20;
      const displayHeight = window.innerHeight * 0.3;

      // 设置canvas的实际像素尺寸
      canvas.width = displayWidth * devicePixelRatio;
      canvas.height = displayHeight * devicePixelRatio;

      // 设置canvas的显示尺寸
      canvas.style.width = displayWidth + 'px';
      canvas.style.height = displayHeight + 'px';

      // 缩放绘图上下文以匹配设备像素比
      ctx.scale(devicePixelRatio, devicePixelRatio);

      // 优化渲染质量，提高清晰度
      ctx.imageSmoothingEnabled = false;
      ctx.textRendering = 'optimizeSpeed';
    }
  }, [windowSize]);
  // end useEffect,设置

  // 画图useEffect
  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');
    if (!(canvas && ctx)) {
      return;
    }
    //const devicePixelRatio = window.devicePixelRatio || 1;
    const displayWidth = window.innerWidth - 20;
    const displayHeight = Math.round(window.innerHeight * 0.3);
    ctx.clearRect(0, 0, displayWidth, displayHeight);
    // 绘制网格：
    ctx.beginPath();

    ctx.lineWidth = 0.3;
    // #endif
    ctx.fillStyle = '#fff';
    ctx.fillRect(0, 0, displayWidth, displayHeight);
    // 抽样，抽
    const zoomX = displayWidth < 400 ? 4 : 2;
    const zoomY = displayWidth < 400 ? 2 : 1;

    let mm = 40 / zoomX;
    ctx.strokeStyle = 'rgba(186, 138, 154, 0.1)';

    let i = 0;
    const gridPath = new Path2D();
    for (i = 0; i < displayWidth / mm; i++) {
      gridPath.moveTo(i * mm, 0);
      gridPath.lineTo(i * mm, displayHeight);
    }
    for (i = 0; i < displayHeight / mm; i++) {
      gridPath.moveTo(0, i * mm);
      gridPath.lineTo(displayWidth, i * mm);
    }
    mm = 200 / zoomX;
    for (i = 0; i < displayWidth / mm; i++) {
      gridPath.moveTo(i * mm, 0);
      gridPath.lineTo(i * mm, displayHeight);
    }
    for (i = 0; i < displayHeight / mm; i++) {
      gridPath.moveTo(0, i * mm);
      gridPath.lineTo(displayWidth, i * mm);
    }
    ctx.stroke(gridPath);
    // 开始绘制波型
    ctx.lineWidth = 0.7;

    i = 0;
    mm = 0;
    //let hh;

    // 当屏足够宽时，下面可能同现负数。
    const standardWaveLength = wave.avrWave[0].values.length;
    mm = Math.round((wave.avrWave[0].values.length / zoomX - displayWidth) / 2);
    //ctx.strokeStyle = "rgba(12, 99, 239, 0.8)";

    const kk =
      typeof qrsIndex === 'string'
        ? standardWaveLength
        : wave.QRSList[qrsIndex].TT - 1024;

    const hh = displayHeight / 2;
    // 用取数，组图，平移，三步进行坐标绘制
    ctx.save();

    const transX = Math.round((displayWidth - standardWaveLength / zoomX) / 2);
    //ctx.translate(transX, hh);
    // 2028:代表2048ms

    const yScale = 2 / (zoomX * zoomY);
    useLeadNames.forEach((leadName) => {
      const leadData = wave.avrWave.filter(
        ({ leadName: ppit }) => leadName === ppit,
      )[0];

      if (!leadData || !leadData.values) {
        console.warn(`导联数据不存在: ${leadName}`);
        return;
      }

      const stdValues = leadData.values;

      const wavePath = new Path2D();
      Array.from(
        { length: Math.round(2028 / zoomX /*displayWidth*/) },
        (_, pi) =>
          pi * zoomX /* 每隔zoomX取一个点，共取：2028 / zoomX 这么多个点 */,
      )
        .map((pig) => {
          // pig :每隔
          // 取数，这里 kk的逻辑特别乱，需要改动
          return (
            (typeof qrsIndex === 'string' || kk < 1024
              ? stdValues[pig]
              : ecgData.data[leadName][pig + kk]) * yScale
          );
        })
        .forEach((pih, il) => {
          if (il <= 0) {
            wavePath.moveTo(il + transX, hh - pih);
          } else {
            wavePath.lineTo(il + transX, hh - pih);
          }
        });

      const color =
        leaderColors.filter(
          ({ name }) => name.toLowerCase() === leadName.toLocaleLowerCase(),
        )[0]?.color || 'rgba(12, 99, 239, 0.8)';
      ctx.strokeStyle = color;

      ctx.stroke(wavePath);
      if (useLeadNames.length === 1) {
        ctx.fillStyle = color;
        ctx.font = '12px serif'; // 设置字体大小
        // 注意：因为translate后，坐标原点可以在画布外面的，这里要放在最左侧
        ctx.fillText(leadName, (transX <= 0 ? 0 - transX : 0) + 10, -8);
      }
    });
    ctx.restore();

    // 绘制垂直线：
    const vLinePath = new Path2D();
    const selectedVLinePath = new Path2D();
    const hoverVLinePath = new Path2D();
    const wHalf = Math.ceil(displayWidth / 2);

    const cxxLines = vLines.filter((line) => line.isPeak === showPeak);
    cxxLines.forEach(({ text, bText, iPos, selected }, index) => {
      let xPos = text !== 'RR' ? wHalf + (iPos - rr) / zoomX : wHalf;
      const xPos2 = Number.isInteger(xPos) ? xPos + 0.5 : xPos;

      const isHovered = hoverIndex === index && isHoveringPeak === showPeak;
      const color = selected ? '#0000FF' : isHovered ? '#FF6B35' : '#787878';
      ctx.fillStyle = color;

      if (selected) {
        selectedVLinePath.moveTo(xPos2, 18);
        selectedVLinePath.lineTo(xPos2, displayHeight - 20);
      } else if (isHovered) {
        hoverVLinePath.moveTo(xPos2, 18);
        hoverVLinePath.lineTo(xPos2, displayHeight - 20);
      } else {
        vLinePath.moveTo(xPos2, 18);
        vLinePath.lineTo(xPos2, displayHeight - 20);
      }

      ctx.font = '12px serif'; // 设置字体大小
      ctx.fillText(text, xPos2 - 8, 16);
      // ctx.font = '8px serif'; // 设置字体大小
      // ctx.fillText(bText, xPos2 - 8, displayHeight - 10);
    });

    // 绘制普通线条
    ctx.strokeStyle = '#787878';
    ctx.lineWidth = 1;
    ctx.stroke(vLinePath);

    // 绘制悬浮线条
    if (hoverIndex >= 0 && isHoveringPeak === showPeak) {
      ctx.strokeStyle = '#FF6B35';
      ctx.lineWidth = 2;
      ctx.stroke(hoverVLinePath);
    }

    // 绘制选中线条
    if (cxxLines.some(({ selected }) => selected)) {
      ctx.strokeStyle = '#0000FF';
      ctx.lineWidth = 2;
      ctx.stroke(selectedVLinePath);
    }

    // 重置线宽
    ctx.lineWidth = 1;
  }, [
    qrsIndex,
    useLeadNames,
    showPeak,
    vLines,
    windowSize,
    hoverIndex,
    isHoveringPeak,
  ]);

  const moveVLine = (dis: number) => {
    const ix = vLines.findIndex(
      ({ selected, isPeak }) => selected && isPeak === showPeak,
    );
    if (ix >= 0) {
      setVLines((pre) =>
        pre.map((u1, index) => ({
          ...u1,
          iPos: u1.iPos + (ix === index ? dis : 0),
        })),
      );
    }
  };

  // end useEffect 画图

  const handlePointerDown = (
    e:
      | React.MouseEvent<HTMLCanvasElement>
      | React.TouchEvent<HTMLCanvasElement>,
  ) => {
    // 如果是触摸事件，阻止默认行为
    if ('touches' in e) {
      e.preventDefault();
    }

    const canvas = canvasRef.current;
    const ctx = canvas?.getContext('2d');
    if (!(canvas && ctx)) {
      return;
    }

    const rectPos = canvas.getBoundingClientRect();
    let clientX: number, clientY: number;

    // 根据事件类型获取坐标
    if ('touches' in e) {
      // 触摸事件
      const touch = e.touches[0];
      clientX = touch.clientX;
      clientY = touch.clientY;
    } else {
      // 鼠标事件
      clientX = e.clientX;
      clientY = e.clientY;
    }
    const pointerX = clientX - rectPos.left;
    const pointerY = clientY - rectPos.top;
    // 修复：使用与绘制时完全相同的displayWidth计算方式
    const displayWidth = window.innerWidth - 20;
    const wHalf = Math.ceil(displayWidth / 2);

    const zoomX = displayWidth < 400 ? 4 : 2;
    //const transX = Math.round(
    //  (displayWidth - wave.avrWave[0].values.length / zoomX) / 2,
    //);

    const filteredLines = vLines.filter((line) => line.isPeak === showPeak);
    let clickedIndex = filteredLines
      .map(({ text, iPos }, index) => {
        let xPos = text !== 'RR' ? wHalf + (iPos - rr) / zoomX : wHalf;
        const xPos2 = Number.isInteger(xPos) ? xPos + 0.5 : xPos;
        // 修复：点击检测时不需要加transX，因为绘制垂直线时也没有加transX
        const inRange = pointerX > xPos2 - 10 && pointerX < xPos2 + 10;

        return inRange ? index : -1;
      })
      .filter((index) => index > -1)[0];

    // 如果找到了点击的线条，需要转换为原始vLines数组中的索引
    if (clickedIndex !== undefined) {
      const originalIndex = vLines.findIndex(
        (line) =>
          line.isPeak === showPeak &&
          line.text === filteredLines[clickedIndex].text,
      );
      clickedIndex = originalIndex;
    }

    // 注意，下面不能用if(clickedIndex)，因为0值被判断为false
    if (clickedIndex !== undefined) {
      // 让他类似于tab，统一行为
      setVLines((pre) =>
        pre.map((u1, index) => ({
          ...u1,
          selected: index === clickedIndex,
        })),
      );
      // 开始拖拽
      setDragState({
        isDragging: true,
        dragIndex: clickedIndex,
        startX: pointerX,
        isPeakMode: showPeak,
      });
    }
  }; // end handlePointerDown;

  // 处理鼠标移动事件
  const handlePointerMove = (
    e:
      | React.MouseEvent<HTMLCanvasElement>
      | React.TouchEvent<HTMLCanvasElement>,
  ) => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const rectPos = canvas.getBoundingClientRect();
    let clientX: number, clientY: number;

    if ('touches' in e) {
      const touch = e.touches[0];
      clientX = touch.clientX;
      clientY = touch.clientY;
    } else {
      clientX = e.clientX;
      clientY = e.clientY;
    }

    const pointerX = clientX - rectPos.left;
    const displayWidth = window.innerWidth - 20;
    const wHalf = Math.ceil(displayWidth / 2);
    const zoomX = displayWidth < 400 ? 4 : 2;

    // 处理拖拽
    if (dragState.isDragging) {
      const deltaX = pointerX - dragState.startX;
      const deltaPos = Math.round(deltaX * zoomX);

      setVLines((prev) =>
        prev.map((line, index) =>
          index === dragState.dragIndex
            ? { ...line, iPos: Math.max(0, line.iPos + deltaPos) }
            : line,
        ),
      );

      setDragState((prev) => ({ ...prev, startX: pointerX }));
      // 注意，这里已经return了
      return;
    }

    // 检测悬浮
    const currentLines = vLines.filter((line) => line.isPeak === showPeak);
    let foundHoverIndex = -1;

    for (let i = 0; i < currentLines.length; i++) {
      const { text, iPos } = currentLines[i];
      let xPos = text !== 'RR' ? wHalf + (iPos - rr) / zoomX : wHalf;
      const xPos2 = Number.isInteger(xPos) ? xPos + 0.5 : xPos;

      if (pointerX > xPos2 - 10 && pointerX < xPos2 + 10) {
        // 找到原始vLines数组中的索引
        foundHoverIndex = vLines.findIndex(
          (line) =>
            line.isPeak === showPeak && line.text === currentLines[i].text,
        );
        break;
      }
    }

    setHoverIndex(foundHoverIndex);
    setIsHoveringPeak(showPeak);

    // 改变鼠标样式
    canvas.style.cursor = foundHoverIndex >= 0 ? 'ew-resize' : 'default';
    if (dragState.isDragging) {
      canvas.style.cursor = 'ew-resize';
    }
  }; // end handlePointerMove

  // 处理鼠标释放事件
  const handlePointerUp = () => {
    const wasDragging = dragState.isDragging;

    setDragState({
      isDragging: false,
      dragIndex: -1,
      startX: 0,
      isPeakMode: false,
    });

    const canvas = canvasRef.current;
    if (canvas) {
      canvas.style.cursor = hoverIndex >= 0 ? 'ew-resize' : 'default';
    }

    // 如果刚完成拖拽，调用分析接口
    if (wasDragging) {
      callAnalysisAPI();
    }
  };

  // 处理鼠标离开事件
  const handlePointerLeave = () => {
    setHoverIndex(-1);
    setIsHoveringPeak(false);
    setDragState({
      isDragging: false,
      dragIndex: -1,
      startX: 0,
      isPeakMode: false,
    });
    const canvas = canvasRef.current;
    if (canvas) {
      canvas.style.cursor = 'default';
    }
  };

  return (
    <div className={styles.container}>
      {/* Canvas */}
      <div className={styles.canvasArea}>
        <canvas
          ref={canvasRef}
          className={styles.canvas}
          onMouseDown={handlePointerDown}
          onMouseMove={handlePointerMove}
          onMouseUp={handlePointerUp}
          onMouseLeave={handlePointerLeave}
          onTouchStart={handlePointerDown}
          onTouchMove={handlePointerMove}
          onTouchEnd={handlePointerUp}
        ></canvas>
        {/* 导联选择按钮 - 右下角 */}
        <Button
          size="small"
          color="default"
          onClick={() => setLeadSelectorVisible(true)}
          style={{
            position: 'absolute',
            bottom: '10px',
            right: '10px',
            zIndex: 10,
            fontSize: '12px',
            padding: '4px 8px',
          }}
        >
          导联选择
        </Button>
      </div>

      {/* 控制区 */}
      <div className={styles.controlArea}>
        <div className={styles.buttonGroup}>
          <span style={{ color: '#1677ff' }}>
            {
              vLines.filter(
                ({ selected, isPeak }) => selected && isPeak === showPeak,
              )[0]?.bText
            }
          </span>
          <Button
            size="mini"
            disabled={!vLines.some(({ selected }) => selected)}
            onClick={() => moveVLine(-2)}
          >
            {'<'}
          </Button>
          <Button
            size="mini"
            disabled={!vLines.some(({ selected }) => selected)}
            onClick={() => moveVLine(2)}
          >
            {'>'}
          </Button>
          <Button
            size="mini"
            onClick={() => {
              // 设置Tab切换状态，避免触发分析
              isTabSwitchingRef.current = true;

              const currentTypeLines = vLines.filter(
                (line) => line.isPeak === showPeak,
              );
              const ix = vLines.findIndex(
                ({ selected, isPeak }) => selected && isPeak === showPeak,
              );

              if (ix < 0) {
                // 没有选中的线条，选中第一个当前类型的线条
                const firstLineIndex = vLines.findIndex(
                  (line) => line.isPeak === showPeak,
                );
                if (firstLineIndex >= 0) {
                  setVLines((pre) =>
                    pre.map((u1, index) => ({
                      ...u1,
                      selected: index === firstLineIndex,
                    })),
                  );
                }
              } else {
                // 找到下一个同类型的线条
                const currentLineInTypeArray = currentTypeLines.findIndex(
                  (line) => vLines[ix].text === line.text,
                );
                const nextInType =
                  currentLineInTypeArray < currentTypeLines.length - 1
                    ? currentLineInTypeArray + 1
                    : 0;
                const nextLineIndex = vLines.findIndex(
                  (line) =>
                    line.isPeak === showPeak &&
                    line.text === currentTypeLines[nextInType].text,
                );

                setVLines((pre) =>
                  pre.map((u1, index) => ({
                    ...u1,
                    selected: index === nextLineIndex,
                  })),
                );
              }
            }}
          >
            Tab
          </Button>
        </div>
      </div>

      {/* 代表波型选择 */}
      {visible && (
        <div className={styles.waveSelector}>
          <Picker
            className={styles.selectDropdown}
            value={[qrsIndex.toString()]}
            onConfirm={(value) => {
              if (value.length > 0) {
                const selectedValue = value[0] as string;
                const i = parseInt(selectedValue);
                setQrsIndex(Number.isNaN(i) ? selectedValue : i);
              }
            }}
            columns={[
              [
                { label: '代表波型', value: 'standard' },
                ...wave.QRSList.map((qrs, index) => ({
                  label: `No:${index + 1}`,
                  value: `${index}`,
                })),
              ],
            ]}
            title="选择波型"
          >
            {(items, { open }) => {
              const currentItem = items[0];
              return (
                <div className={styles.pickerTrigger} onClick={open}>
                  {currentItem ? currentItem.label : '代表波型'}
                </div>
              );
            }}
          </Picker>
        </div>
      )}

      {/* 显示峰值 */}
      {visible && (
        <div className={styles.showPeak}>
          <Checkbox
            checked={showPeak}
            onChange={(checked) => {
              setShowPeak(checked);
            }}
          >
            显示峰值
          </Checkbox>
        </div>
      )}

      {/* 测量数据 */}
      <div className={styles.measurementArea}>
        <div className={styles.measurementGrid}>
          {ingEcgParams.map(({ param, value, status }, index) => (
            <div className={styles.measurementItem} key={index}>
              <span className={styles.label}>{param.label}</span>
              <span
                className={styles.value}
                style={{
                  backgroundColor: !status
                    ? '#FFFFFF'
                    : status.value === 'reduced'
                    ? '#FFFF00'
                    : status.value === 'elevated'
                    ? '#FF0000'
                    : '#FFFFFF',
                }}
              >
                {value}
              </span>
              <span className={styles.unit}>{param.unit}</span>
            </div>
          ))}
        </div>
      </div>

      {/* 分析结果 */}
      <div className={styles.analysisArea}>
        <div className={styles.analysisContent}>
          <Space direction={'vertical'}>
            {ingAutoAnalysisResult.split(/\r\n/g).map((l, i) => (
              <span key={i}>{l}</span>
            ))}
          </Space>
        </div>
      </div>

      {/* 导联选择弹窗 */}
      <Popup
        visible={leadSelectorVisible}
        onMaskClick={() => setLeadSelectorVisible(false)}
        position="right"
        bodyStyle={{
          top: '20%',
          borderRadius: '8px',
          height: '260px',
          padding: 16,
        }}
      >
        <div style={{ marginBottom: '16px' }}>
          <h3 style={{ margin: '0 0 16px 0', textAlign: 'center' }}>
            导联选择
          </h3>
          {/* 导联选择模式 */}
          <div style={{ marginBottom: '16px' }}>
            <div
              style={{
                marginBottom: '8px',
                fontSize: '14px',
                fontWeight: 'bold',
              }}
            >
              选择模式
            </div>
            <Radio.Group
              value={selectMode}
              onChange={(value) => {
                setSelectMode(value as 'single' | 'multi' | 'all');

                if (value === 'all') {
                  // 全部导联模式
                  setShowAllLeads(true);
                  setIsMultiSelect(false);
                  setActiveTab('allLead');
                  setUseLeadNames(wave.avrWave.map((aw) => aw.leadName));
                } else if (value === 'multi') {
                  // 多选模式
                  setShowAllLeads(false);
                  setIsMultiSelect(true);
                  // 保持当前选中的导联
                } else {
                  // 单选模式
                  setShowAllLeads(false);
                  setIsMultiSelect(false);
                  // 如果当前activeTab是'allLead'，则选择第一个有效的导联
                  const validLeadName =
                    activeTab === 'allLead'
                      ? wave.avrWave[0].leadName
                      : activeTab;
                  setActiveTab(validLeadName);
                  setUseLeadNames([validLeadName]);
                }
              }}
            >
              <Space direction="horizontal" style={{ flexWrap: 'wrap' }}>
                <Radio value="single">单选</Radio>
                <Radio value="multi">多选</Radio>
                <Radio value="all">全部导联</Radio>
              </Space>
            </Radio.Group>
          </div>

          {/* 导联标签 */}
          <div
            style={{
              display: 'flex',
              flexWrap: 'wrap',
              gap: '8px',
              marginBottom: '16px',
            }}
          >
            {wave.avrWave
              .map((aw) => aw.leadName)
              .map((leadName) => {
                const isSelected = useLeadNames.includes(leadName);
                const isActive = activeTab === leadName;
                const leaderColor =
                  leaderColors.find((lc) => lc.name === leadName)?.color ||
                  '#000000';
                return (
                  <Tag
                    key={leadName}
                    color={leaderColor}
                    fill={isSelected ? 'solid' : 'outline'}
                    onClick={() => {
                      if (selectMode === 'all') {
                        // 如果是全部导联模式，禁用点击
                        return;
                      }
                      if (selectMode === 'multi') {
                        // 多选模式：切换选中状态
                        if (isSelected) {
                          // 如果已选中，则取消选中（但至少保留一个）
                          if (useLeadNames.length > 1) {
                            setUseLeadNames(
                              useLeadNames.filter((name) => name !== leadName),
                            );
                            // 如果取消选中的是当前activeTab，需要更新activeTab
                            if (activeTab === leadName) {
                              const remainingLeads = useLeadNames.filter(
                                (name) => name !== leadName,
                              );
                              setActiveTab(remainingLeads[0]);
                            }
                          }
                        } else {
                          // 如果未选中，则添加到选中列表
                          setUseLeadNames([...useLeadNames, leadName]);
                          setActiveTab(leadName);
                        }
                      } else {
                        // 单选模式：只选中当前tag
                        setActiveTab(leadName);
                        setUseLeadNames([leadName]);
                        // 单选时选择后直接关闭弹窗
                        setLeadSelectorVisible(false);
                      }
                    }}
                    style={{
                      cursor: selectMode === 'all' ? 'not-allowed' : 'pointer',
                      border:
                        isActive && selectMode === 'single'
                          ? '2px solid #1677ff'
                          : undefined,
                      fontWeight: isSelected ? 'bold' : 'normal',
                      opacity: selectMode === 'all' ? 0.5 : 1,
                      fontSize: '14px',
                      padding: '4px 8px',
                    }}
                  >
                    {leadName}
                  </Tag>
                );
              })}
          </div>

          {/* 弹窗底部按钮 */}
          <div
            style={{ display: 'flex', gap: '8px', justifyContent: 'center' }}
          >
            <Button
              size="small"
              color="primary"
              onClick={() => setLeadSelectorVisible(false)}
            >
              确定
            </Button>
          </div>
        </div>
      </Popup>

      {/* 底部按钮 */}
      <div className={styles.footer}>
        <Button
          size="small"
          color="primary"
          className={styles.saveBtn}
          onClick={() => {
            setEcgParams(ingEcgParams);
            setAutoAnalysisResult(ingAutoAnalysisResult);
            setVerticalLines(
              vLines.map(({ iPos, type, text }) => ({
                position: iPos,
                type: { value: type, label: type },
              })),
            );
            onSave('自动分析页面关系！');
            //setVerticalLines()
          }}
        >
          保存
        </Button>
        <Button size="small" className={styles.cancelBtn} onClick={onClose}>
          取消
        </Button>
      </div>
    </div>
  );
};

export default AnalysisOverlay;
